import { queryAttribute, removeRule, addAttribute } from '../services/api';

export default {
  namespace: 'attribute',

  state: {
    list: [],
    pagination: undefined,
    loading: true,
  },

  effects: {
    *fetch({ payload }, { call, put }) {
      yield put({
        type: 'changeLoading',
        payload: true,
      });
      const response = yield call(queryAttribute, payload);
      yield put({
        type: 'loadAttrList',
        payload: response,
      });
      yield put({
        type: 'changeLoading',
        payload: false,
      });
    },
    *add({ payload, callback }, { call, put }) {
      yield put({
        type: 'changeLoading',
        payload: true,
      });
      const response = yield call(addAttribute, payload);
      yield put({
        type: 'saveItem',
        payload: response,
      });
      yield put({
        type: 'changeLoading',
        payload: false,
      });

      if (callback) callback();
    },
    *remove({ payload, callback }, { call, put }) {
      yield put({
        type: 'changeLoading',
        payload: true,
      });
      const response = yield call(removeRule, payload);
      yield put({
        type: 'save',
        payload: response,
      });
      yield put({
        type: 'changeLoading',
        payload: false,
      });

      if (callback) callback();
    },
  },

  reducers: {
    loadAttrList(state, { payload }) {
      return {
        ...state,
        list: payload.attr_list,
        pagination: payload.pagination,
      };
    },
    saveItem(state, { payload }) {
      const prevList = state.list;
      prevList.push(payload);
      return {
        ...state,
        list: prevList,
      };
    },
    changeLoading(state, { payload }) {
      return {
        ...state,
        loading: payload,
      };
    },
  },
};
